document.addEventListener('DOMContentLoaded', function() {
  // DOM元素
  const navDashboard = document.getElementById('nav-dashboard');
  const navHistory = document.getElementById('nav-history');
  const navSettings = document.getElementById('nav-settings');
  
  const dashboardSection = document.getElementById('dashboard-section');
  const historySection = document.getElementById('history-section');
  const settingsSection = document.getElementById('settings-section');
  
  const startBtn = document.getElementById('start-btn');
  const stopBtn = document.getElementById('stop-btn');
  
  const statusDot = document.getElementById('status-indicator');
  const statusText = document.getElementById('status-text');
  const recordingStatus = document.getElementById('recording-status');
  const screenshotIntervalDisplay = document.getElementById('screenshot-interval');
  const journalIntervalDisplay = document.getElementById('journal-interval');
  const historyCountDisplay = document.getElementById('history-count');
  
  const settingsForm = document.getElementById('settings-form');
  const screenshotIntervalInput = document.getElementById('screenshot-interval-input');
  const journalIntervalInput = document.getElementById('journal-interval-input');
  const historyCountInput = document.getElementById('history-count-input');
  
  const startDateInput = document.getElementById('start-date');
  const endDateInput = document.getElementById('end-date');
  const typeFilterInput = document.getElementById('type-filter');
  const filterBtn = document.getElementById('filter-btn');
  
  const journalsContainer = document.getElementById('journals-container');
  const recentJournalContainer = document.getElementById('recent-journal');
  
  // 不设置日期选择器的默认值，以便进入历史记录页面时显示所有手账
  
  // 导航切换
  function showSection(section) {
    [dashboardSection, historySection, settingsSection].forEach(s => {
      s.classList.add('d-none');
    });
    section.classList.remove('d-none');
  }
  
  navDashboard.addEventListener('click', function(e) {
    e.preventDefault();
    showSection(dashboardSection);
    updateNavActive(this);
    fetchStatus(); // 更新状态
  });
  
  navHistory.addEventListener('click', function(e) {
    e.preventDefault();
    showSection(historySection);
    updateNavActive(this);
    loadJournals(); // 加载历史记录
  });
  
  navSettings.addEventListener('click', function(e) {
    e.preventDefault();
    showSection(settingsSection);
    updateNavActive(this);
    loadSettings(); // 加载设置
  });
  
  function updateNavActive(activeNav) {
    [navDashboard, navHistory, navSettings].forEach(nav => {
      nav.classList.remove('active');
      nav.classList.add('text-white');
    });
    activeNav.classList.add('active');
    activeNav.classList.remove('text-white');
  }
  
  // API调用函数
  async function fetchStatus() {
    try {
      const response = await fetch('/api/status');
      const data = await response.json();
      updateStatusDisplay(data);
    } catch (error) {
      console.error('获取状态失败:', error);
    }
  }
  
  async function startRecording() {
    try {
      const response = await fetch('/api/control', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ action: 'start' })
      });
      const data = await response.json();
      if (data.success) {
        fetchStatus();
      } else {
        alert(data.message || '开始记录失败');
      }
    } catch (error) {
      console.error('开始记录失败:', error);
      alert('开始记录失败，请检查服务器状态');
    }
  }
  
  async function stopRecording() {
    try {
      const response = await fetch('/api/control', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ action: 'stop' })
      });
      const data = await response.json();
      if (data.success) {
        fetchStatus();
      } else {
        alert(data.message || '停止记录失败');
      }
    } catch (error) {
      console.error('停止记录失败:', error);
      alert('停止记录失败，请检查服务器状态');
    }
  }
  
  async function saveSettings() {
    const screenshotInterval = parseInt(screenshotIntervalInput.value);
    const journalInterval = parseInt(journalIntervalInput.value);
    const historyCount = parseInt(historyCountInput.value);
    
    // 验证输入
    if (screenshotInterval < 1 || screenshotInterval > 60) {
      alert('截图间隔必须在1-60分钟之间');
      return false;
    }
    
    if (journalInterval < 1 || journalInterval > 240) {
      alert('手账生成间隔必须在5-240分钟之间');
      return false;
    }
    
    if (historyCount < 0 || historyCount > 10) {
      alert('历史附带条目数必须在0-10之间');
      return false;
    }
    
    if (screenshotInterval > journalInterval) {
      alert('截图间隔必须小于或等于手账间隔');
      return false;
    }
    
    try {
      const response = await fetch('/api/settings', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          screenshotInterval,
          journalInterval,
          historyCount
        })
      });
      
      const data = await response.json();
      if (data.success) {
        alert('设置已保存');
        fetchStatus();
        return true;
      } else {
        alert(data.error || '保存设置失败');
        return false;
      }
    } catch (error) {
      console.error('保存设置失败:', error);
      alert('保存设置失败，请检查服务器状态');
      return false;
    }
  }
  
  async function loadSettings() {
    try {
      const response = await fetch('/api/status');
      const data = await response.json();
      
      screenshotIntervalInput.value = data.settings.screenshotInterval;
      journalIntervalInput.value = data.settings.journalInterval;
      historyCountInput.value = data.settings.historyCount;
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  }
  
  async function loadJournals() {
    const startDate = startDateInput.value;
    const endDate = endDateInput.value;
    const type = typeFilterInput.value;
    
    try {
      let url = '/api/journals?';
      if (startDate) url += `startDate=${startDate}&`;
      if (endDate) url += `endDate=${endDate}&`;
      if (type) url += `type=${type}`;
      
      const response = await fetch(url);
      const journals = await response.json();
      
      renderJournals(journals);
    } catch (error) {
      console.error('加载历史记录失败:', error);
      journalsContainer.innerHTML = '<p class="text-center text-danger my-5">加载历史记录失败</p>';
    }
  }
  
  async function loadJournalDetail(journalId) {
    try {
      const response = await fetch(`/api/journal/${journalId}`);
      const journal = await response.json();
      
      renderJournalDetail(journal);
      
      // 显示模态框
      const modal = new bootstrap.Modal(document.getElementById('journal-detail-modal'));
      modal.show();
    } catch (error) {
      console.error('加载手账详情失败:', error);
      alert('加载手账详情失败');
    }
  }
  
  // 更新UI显示
  function updateStatusDisplay(data) {
    const isRecording = data.isRecording;
    
    // 更新状态指示器
    if (isRecording) {
      statusDot.classList.add('active');
      statusText.textContent = '记录中';
      recordingStatus.textContent = '记录中';
      startBtn.disabled = true;
      stopBtn.disabled = false;
    } else {
      statusDot.classList.remove('active');
      statusText.textContent = '未记录';
      recordingStatus.textContent = '未开始';
      startBtn.disabled = false;
      stopBtn.disabled = true;
    }
    
    // 更新设置显示
    screenshotIntervalDisplay.textContent = `${data.settings.screenshotInterval}分钟`;
    journalIntervalDisplay.textContent = `${data.settings.journalInterval}分钟`;
    historyCountDisplay.textContent = data.settings.historyCount;
    
    // 加载最近手账
    loadRecentJournal();
  }
  
  async function loadRecentJournal() {
    try {
      const response = await fetch('/api/journals?');
      const journals = await response.json();
      
      if (journals.length > 0) {
        const recent = journals[0]; // 最新的一条
        recentJournalContainer.innerHTML = `
          <div class="d-flex align-items-center mb-2">
            <span class="journal-type journal-type-${recent.type} me-2">${recent.type}</span>
            <span class="text-muted small">${formatDateTime(recent.timestamp)}</span>
          </div>
          <div class="mb-1 markdown-content">${marked.parse(recent.summary.substring(0, 150))}${recent.summary.length > 150 ? '...' : ''}</div>
          <button class="btn btn-sm btn-outline-primary mt-2" onclick="window.loadJournalDetail('${recent.id}')">查看详情</button>
        `;
      } else {
        recentJournalContainer.innerHTML = '<p class="text-muted">暂无最近手账</p>';
      }
    } catch (error) {
      console.error('加载最近手账失败:', error);
      recentJournalContainer.innerHTML = '<p class="text-danger">加载失败</p>';
    }
  }
  
  function renderJournals(journals) {
    if (journals.length === 0) {
      journalsContainer.innerHTML = '<p class="text-center text-muted my-5">暂无历史记录</p>';
      return;
    }
    
    let html = '';
    journals.forEach(journal => {
      html += `
        <div class="card journal-card mb-3" onclick="window.loadJournalDetail('${journal.id}')">
          <div class="card-body">
            <div class="d-flex justify-content-between align-items-start">
              <div>
                <span class="journal-type journal-type-${journal.type} me-2">${journal.type}</span>
                <span class="text-muted small">${formatDateTime(journal.timestamp)}</span>
              </div>
              <span class="badge bg-secondary">${journal.duration}分钟</span>
            </div>
            <div class="card-text mt-2 markdown-content">${marked.parse(journal.summary.substring(0, 200))}${journal.summary.length > 200 ? '...' : ''}</div>
          </div>
        </div>
      `;
    });
    
    journalsContainer.innerHTML = html;
  }
  
  function renderJournalDetail(journal) {
    const detailContent = document.getElementById('journal-detail-content');
    
    let html = `
      <div class="mb-3">
        <div class="d-flex justify-content-between align-items-center mb-3">
          <div>
            <span class="journal-type journal-type-${journal.type} me-2">${journal.type}</span>
            <span class="text-muted">${formatDateTime(journal.timestamp)}</span>
          </div>
          <span class="badge bg-secondary">${journal.duration}分钟</span>
        </div>
        <div class="card">
          <div class="card-body">
            <h6 class="card-subtitle mb-2 text-muted">AI分析摘要</h6>
            <div class="card-text markdown-content">${marked.parse(journal.summary)}</div>
          </div>
        </div>
      </div>
    `;
    
    detailContent.innerHTML = html;
  }
  
  // 辅助函数
  function formatDateTime(dateTimeStr) {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  }
  
  // 事件监听
  startBtn.addEventListener('click', startRecording);
  stopBtn.addEventListener('click', stopRecording);
  
  settingsForm.addEventListener('submit', function(e) {
    e.preventDefault();
    saveSettings();
  });
  
  filterBtn.addEventListener('click', loadJournals);
  
  // 暴露给全局以便在HTML中调用
  window.loadJournalDetail = loadJournalDetail;
  
  // 初始化
  fetchStatus();
});